local FateStone = class("FateStone")


function FateStone:ctor()
end

function FateStone:init()
    self.stones = GD:queryFateStones()
    self.processes = GD:queryFateStoneProgresses()
    self.chapters = {}
    self.maxChapterIndex = 0

    for i, v in pairs(self.stones) do
        local tid = checknumber(v.taskID)
        local chapter = self.chapters[checknumber(v.chapter)] or {}
        local tasks = chapter.tasks or {}

        chapter.index = checknumber(v.chapter)
        if self.maxChapterIndex < chapter.index then
            self.maxChapterIndex = chapter.index
        end
        if checknumber(chapter.maxTaskID) < tid then
            chapter.maxTaskID = tid
        end
        table.insert(tasks, tid)

        chapter.tasks = tasks
        self.chapters[checknumber(v.chapter)] = chapter
    end

    for i, v in pairs(self.processes) do
        local chapter = self.chapters[checknumber(v.chapter)] or {}
        chapter.progresses = chapter.progresses or {}
        table.insert(chapter.progresses, {cfg=v})

        self.chapters[checknumber(v.chapter)] = chapter
    end

    for k, v in pairs(self.chapters) do
        table.sort(v.progresses, function(a, b) return a.cfg.ID < b.cfg.ID end )
        table.sort(v.tasks, function(a, b) return a < b end)
    end
end

function FateStone:setUUID(uuid)
    self._uuid = uuid
end

function FateStone:getSortedChapters()
    local achapters = {}
    for k, c in pairs(self.chapters) do
        table.insert(achapters, c)
    end
    table.sort(achapters, function(a, b) return a.index < b.index end)

    return achapters
end

function FateStone:getCurrnetFateStone()
    self:refreshFateStoneStatus()

    local r = self:getChapter(self:getCurChapterID())
    if r then
        return r
    end

    local achapters = self:getSortedChapters()
    return achapters[#achapters]
end

function FateStone:getLastFateStone()
    local achapters = self:getSortedChapters()
    return achapters[#achapters]
end

function FateStone:getFirstRedChapter()
    local achapters = self:getSortedChapters()
    if self._openChapter then
        local r = achapters[self._openChapter]
        self._openChapter = nil
        if r then
            return r 
        end
    end
    for i, c in ipairs(achapters) do
        for _, p in ipairs(c.progresses) do
            if self:hasRewarded(p.cfg.ID) then
                return c
            end
        end
    end
    return self:getCurrnetFateStone()
end

function FateStone:getCurChapterID()
    local cid = checknumber(UD:getCurTask().id)
    return math.fmod(math.floor(cid/10000), 10)
end

function FateStone:getChapter(aIndex)
    -- self:refreshFateStoneStatus()

    for k, c in pairs(self.chapters) do
        if c.index == aIndex then
            return c
        end
    end
end

function FateStone:refreshFateStoneStatus()
    local cid = checknumber(UD:getCurTask().id)
    local lastShowTaskID = checknumber(app:getValue(self:GetLastTaskStoreKey(), "0"))
    local maxSavedID = lastShowTaskID

    for k, c in pairs(self.chapters) do
        if not c.finished then
            c.begined = c.index == 1
            c.splashCount = 0
            c.splashedCount = 0
            for _, t in ipairs(c.tasks) do
                if t < cid then
                    c.begined = true
                    if t > lastShowTaskID then
                        c.splashCount = checknumber(c.splashCount) + 1
                    else
                        c.splashedCount = checknumber(c.splashedCount) + 1
                    end

                    if maxSavedID < t then
                        maxSavedID = t
                        app:saveValue(self:GetLastTaskStoreKey(), tostring(t))     
                    end
                end
            end
            c.finishedCount = checknumber(c.splashCount) + checknumber(c.splashedCount)
            if c.maxTaskID < cid then
                c.finished = true
            end
        end
    end
end

function FateStone:getFateStoneStatus()
    local ret = {
        currentChapter = 1,
        canRewardedCount = 0,
        rewardedCount = 0,
        progresses = {},
        finishedCount = 0
    }

    local cid = checknumber(UD:getCurTask().id)
    local lastShowTaskID = checknumber(app:getValue(self:GetLastTaskStoreKey(), "0"))
    local maxSavedID = lastShowTaskID

    for i, v in pairs(self.stones) do
        local chapter = self.chapters[checknumber(v.chapter)] or {}
        local tid = checknumber(v.taskID)
        if not chapter.finished then
            chapter.finished = tid < cid
        end

        if cid > tid then
            if lastShowTaskID < tid then --刚解锁的石板
                chapter.canRewardedCount = chapter.canRewardedCount + 1
            else
                chapter.rewardedCount = chapter.rewardedCount + 1
            end
            
            if maxSavedID < tid then
                maxSavedID = tid
                app:saveValue(self:GetLastTaskStoreKey(), tostring(v.taskID))     
            end            
        else--未完成
            chapter.currentChapter = v.chapter
            break --第一个没完成的任务，后面肯定也没完成
        end
    end

    ret.finishedCount = ret.canRewardedCount + ret.rewardedCount

    for i, v in pairs(self.processes) do
        local chapter = self.chapters[checknumber(v.chapter)] or {}
        local st = {cfg = v, finished = checknumber(v.progressValue) <= ret.finishedCount}
        table.insert(chapter.progresses, st)      
    end

    table.sort(ret.progresses, function(a, b)
        return a.cfg.ID < b.cfg.ID
        end)

    return ret
end

function FateStone:GetEvtRewardsChangeName()
    return "reward.fatestone.rewardschange"
end

function FateStone:GetLastTaskStoreKey()
    return "rewardFatestoneLastshowtaskid"..tostring(UD.uid)
end

function FateStone:hasRewarded(aID)
    aID = checknumber(aID)
    if self.rewardsToGet then
        return table.indexof(self.rewardsToGet, aID)
    end
end

function FateStone:checkRedPoint()
    if self.rewardsToGet and  #self.rewardsToGet > 0 then
        return true
    end

    return false
end

function FateStone:refreshRedPoint()
    local redPoint = false
    if self:checkRedPoint() then
        redPoint = true
    end

    if self._uuid then
        local rewardModel = app:getInst("RewardModel")
        rewardModel:setRedPoint(self._uuid,redPoint)
    end

end

function FateStone:getRewardChapter(aId)
    local p = self.processes[tostring(aId)]
    return checknumber(p.chapter)
end

-- 一章奖励领完时，播特效，因此记录领取状态
function FateStone:refreshShareStatus()
    if self.initRewardsToGet == nil then
        self.initRewardsToGet = self.rewardsToGet
    end

    self.finishedchapter = {}
    local newcs = {}
    for i, v in ipairs(self.rewardsToGet) do
        newcs[self:getRewardChapter(v)] = true
    end

    for i, v in ipairs(self.initRewardsToGet) do
        if not newcs[self:getRewardChapter(v)] then
            self.finishedchapter[self:getRewardChapter(v)] = true
        end
    end
    self.initRewardsToGet = self.rewardsToGet
end

function FateStone:reqRewards()
    app.session:request("pb_activity.C2S_FatestoneReceiveAwards", {}, function(msg)
        self.rewardsToGet = msg.fatestone_progress_ids

        self:refreshRedPoint()
        self:refreshShareStatus()
        EM:notify(self:GetEvtRewardsChangeName())
    end, nil, function(errMsg)
    end)
end

function FateStone:reqGetReward(id)
    app.session:request("pb_activity.C2S_GetFatestoneAward", {fatestone_progress_id = id}, function(msg)
        if msg.ok then
            self:reqRewards()
        end
        -- dump(msg, "C2S_GetFatestoneAward")
    end, {block = true}, function(errMsg)
    end)
end

return FateStone